package org.example.socket;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.charset.Charset;

public class ServerSocketManager {

    private int connectTimeoutMillis = 5 * 1000;
    private IoSession mIoSession;
    public void initSocket(){
        NioSocketAcceptor acceptor = new NioSocketAcceptor();
        acceptor.setHandler(new ServerSocketHandler());
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        //chain.addLast("logger", new LoggingFilter());
        //chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),
        //                LineDelimiter.NUL, LineDelimiter.NUL)));
        SocketSessionConfig dcfg = acceptor.getSessionConfig();
        dcfg.setReuseAddress(true);
        try {
            acceptor.bind(new InetSocketAddress(8989));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static ServerSocketManager instance = new ServerSocketManager();
    private ServerSocketManager() {}

    public static ServerSocketManager getInstance(){
        return instance;
    }
    public void setIoSession(IoSession ioSession) {
        mIoSession = ioSession;
    }

    public IoSession getSession() {
        return mIoSession;
    }

    public void sendData(Object obj) {
        if (mIoSession != null && mIoSession.isConnected()) {
            mIoSession.write(obj);
        }
    }
}
